const http = require('http');
const httpProxy = require('http-proxy');
const cron = require('cron');
const axios = require('axios');

const s1 = 'http://localhost:8081';
const s2 = 'http://localhost:8082';

let target = s1;
let testApi = '/api-v1/mes/metrics'

// 创建一个代理服务器实例，并配置目标服务器的地址
const proxy = httpProxy.createProxyServer({
  //target: 'http://localhost:8000',
  //changeOrigin: true
});



// 创建一个 HTTP 服务器，并在请求到达时触发代理服务器的转发
const server = http.createServer((req, res) => {
  //console.log(req)
  proxy.web(req, res, { target }, function (err) {
    console.log(err)
  });
});

//proxy.on('proxyReq', function(proxyReq, req, res, options) {
//console.log(proxyReq)
//});

proxy.on('proxyRes', function (proxyRes, req, res) {
 res.setHeader('X-Target-Server', target)
});

const port = 2000;

server.listen(port, () => {
  console.log(`Proxy server is running on port ${port}`);
});


new cron.CronJob(
  '* * * * * *', // cronTime
  function () {

    axios.get(s1 + testApi, { timeout: 1 * 1000 }).then(res => {
    }).catch(err => {
       target = s2
    })

    axios.get(s2 + testApi, { timeout: 1 * 1000 }).then(res => {

    }).catch(err => {
       target = s1
    })

  }, // onTick
  null, // onComplete
  true, // start
  'Asia/Shanghai' // timeZone
);